package com.example.starter.weixin.util;

import cn.hutool.http.HttpUtil;
import com.example.starter.util.JSONUtil;
import com.example.starter.weixin.pojo.WxPhone;
import com.example.starter.weixin.pojo.WxSession;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王令
 * @since 2023/4/9
 */
public class WxUtil {

    public static String obtainAccessToken(String appid, String secret) {
        final String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        return (String) JSONUtil.parseToObjMap(HttpUtil.get(url)).get("access_token");
    }

    public static WxPhone obtainPhoneNumber(String access_token, String code) {
        final String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        final Map<String, Object> body = new HashMap<>();
        body.put("code", code);
        return JSONUtil.parse(HttpUtil.post(url, JSONUtil.toJsonStr(body)), WxPhone.class);
    }

    public static WxSession login(String appid, String secret, String js_code) {
        final String url = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + appid + "&secret=" + secret + "&js_code=" + js_code;
        return JSONUtil.parse(HttpUtil.get(url), WxSession.class);
    }
}
